/**
 * (c) Copyright Ascensio System SIA 2025
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zzvcom.office.controllers;

import com.zzvcom.office.documentserver.storage.FileStorageMutator;
import com.zzvcom.office.documentserver.storage.FileStoragePathBuilder;
import com.zzvcom.office.documentserver.util.Misc;
import com.zzvcom.office.dto.FormatsList;
import com.zzvcom.office.entities.OfficeFile;
import com.zzvcom.office.entities.User;
import com.zzvcom.office.sdk.manager.DocumentManager;
import com.zzvcom.office.sdk.manager.UrlManager;
import com.zzvcom.office.services.OfficeFileServices;
import com.zzvcom.office.services.UserServices;
import com.zzvcom.office.util.LogSdkItemUtil;
import com.zzvcom.office.vo.FileVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@CrossOrigin("*")
@Controller
@Slf4j
public class IndexController {

    @Autowired
    private FileStorageMutator storageMutator;

    @Autowired
    private FileStoragePathBuilder storagePathBuilder;

    @Autowired
    private Misc mistUtility;

    @Autowired
    private UserServices userService;

    @Autowired
    private DocumentManager documentManager;

    @Autowired
    private UrlManager urlManager;

    @Value("${url.converter}")
    private String urlConverter;

    @Value("${url.editor}")
    private String urlEditor;

    @Value("${files.docservice.languages}")
    private String langs;

    @Value("${server.version}")
    private String serverVersion;

    @Value("${enable-forgotten}")
    private String enableForgotten;
    @Autowired
    private OfficeFileServices officeFileServices;
    @Autowired
    private LogSdkItemUtil logSdkItemUtil;


    @GetMapping("${url.index}")
    public String index(final Model model) {
        //查询数据库中所有的文件
        List<OfficeFile> all = officeFileServices.findAll();
        Map<String, OfficeFile> fileNameMap = all.stream().collect(Collectors.toMap(OfficeFile::getName, Function.identity()));
        //java.io.File[] files = storageMutator.getStoredFiles();  // get all the stored files from the storage
        List<String> docTypes = new ArrayList<>();
        List<Boolean> filesEditable = new ArrayList<>();
        List<String> versions = new ArrayList<>();
        List<Boolean> isFillFormDoc = new ArrayList<>();
        List<String> langsAndKeys = Arrays.asList(langs.split("\\|"));

        Map<String, String> languages = new LinkedHashMap<>();

        langsAndKeys.forEach((str) -> {
            String[] couple = str.split(":");
            languages.put(couple[0], couple[1]);
        });
        List<User> users = userService.findAll();  // get a list of all the users

       /* String tooltip = users.stream()  // get the tooltip with the user descriptions
                .map(user -> mistUtility.convertUserDescriptions(user.getName(),
                        user.getDescriptions()))  // convert user descriptions to the specified format
                .collect(Collectors.joining());*/
        List<FileVo> fileVoList = new ArrayList<>();
        for (OfficeFile officeFile : all) {
            String fileLocation = storagePathBuilder.getFileLocation(officeFile, officeFile.getName());
            File file = new File(fileLocation);
            if (file.exists()) {
                FileVo fileVo = new FileVo();
                fileVoList.add(fileVo);
                fileVo.setOfficeFile(officeFile);
                fileVo.setFile(file);

                String fileName = officeFile.getName();
                String doctype = documentManager
                        .getDocumentType(fileName)
                        .toString()
                        .toLowerCase();
                fileVo.setDocType(doctype);
                // add a document type of each file to the list
                docTypes.add(doctype);

                boolean editable = documentManager.isEditable(fileName);
                filesEditable.add(editable);  // specify if a file is editable or not
                fileVo.setEditable(editable);
                //历史文件目录
                String fileLocationHistoryDir = storagePathBuilder.getFileLocationHistoryDir(officeFile, fileName);

                int version = storagePathBuilder.getFileVersion(fileLocationHistoryDir, false);
                versions.add("[" + version + "]");  // add a file version to the list
                fileVo.setVersion("[" + version + "]");
                boolean fillable = documentManager.isFillable(fileName);
                isFillFormDoc.add(fillable);

            }
        }
        log.info("files={}", fileVoList);
        log.info("docTypes={}", docTypes);
        log.info("filesEditable={}", filesEditable);
        // add all the parameters to the model
        model.addAttribute("isFillFormDoc", isFillFormDoc);
        model.addAttribute("versions", versions);
        model.addAttribute("files", fileVoList);
        model.addAttribute("docTypes", docTypes);
        model.addAttribute("filesEditable", filesEditable);
        model.addAttribute("datadocs", urlManager.getDocumentServerPreloaderApiUrl());
        //暂时注释
        //  model.addAttribute("tooltip", tooltip);
        model.addAttribute("users", users);
        model.addAttribute("languages", languages);
        model.addAttribute("serverVersion", serverVersion);
        model.addAttribute("enableForgotten", Boolean.valueOf(enableForgotten));

        return "index.html";
    }

    /**
     * 获取配置参数
     *
     * @param request
     * @return
     */
    @PostMapping("/config")
    @ResponseBody
    public HashMap<String, String> configParameters(HttpServletRequest request) {
        HashMap<String, String> configuration = new HashMap<>();
        configuration.put("UrlConverter", request.getContextPath() + urlConverter);
        configuration.put("UrlEditor", request.getContextPath() + urlEditor);
        return configuration;
    }

    /**
     * 获取所有支持的格式
     *
     * @return
     */
    @GetMapping("/formats")
    @ResponseBody
    public ResponseEntity<FormatsList> formats() {
        FormatsList list = new FormatsList(documentManager.getFormats());
        logSdkItemUtil.log(list);
        return ResponseEntity.ok(list);
    }
}
